<?php

namespace Home\Controller;

use Think\Controller;

/**
 * Description of 父类控制器实例
 * @author songanwei
 * @date 2015-12-31
 */
class ParentController extends \Common\Controller\BaseController {

    protected $hotelId;

    protected function _initialize() {
        parent::_initialize();
        $this->hotelId = I('param.hotel', 0);
        $this->checkLogin();
        $this->assignHotel();
        $this->assignUser();
        $this->adminAuthority = $this->assignAuthority();
        $this->checkLanguage();
        $this->switchTimeUtc();
        
    }

    /**
     * 言切时区
     * @modify wenhui 2017-06-22    创建
     */
    protected function switchTimeUtc() {
        // 客栈时区
        $hotelEntityInfo= D('HotelEntity')->getInfo($this->hotelId);
        $universalTimeModel = D('UniversalTime');
        $universalTimeInfo = $universalTimeModel->field('etc')->where(['id' => $hotelEntityInfo['universaltime_id']])->find();
        $universalTimeEtc = $universalTimeInfo ? $universalTimeInfo['etc'] : 'Etc/GMT-8';
        date_default_timezone_set($universalTimeEtc);
    }

    /**
     * 根据语言切换web页面语言
     * @modify trainyao 2016-02-24    创建
     */
    protected function checkLanguage() {
        if (!in_array(LANG_SET, array('zh_cn', 'en_us', 'zh_tw'))) {
            $this->theme('en_us');
        } else {
            $this->theme(LANG_SET);
        }
    }

    /**
     * 判断是否登录，未登录跳转到登录页面
     * @modify songanwei 2015-01-09
     */
    protected function checkLogin() {
        $userId = getUserId();
        // session和cookie都没有登录
        if (!$userId && !$this->checkRememberMe()) {
            if (IS_AJAX) {
                returnJson(403, 203, 'error');
            } else {
                redirect('/login.html');
            }
        }
    }

    /**
     * 判断是否登录，已登录跳转到房态页面
     * @modify AmosZhong 2015-01-28
     */
    protected function checkLogout() {
        $userId = getUserId();
        // session或者cookie有登录
        if (!empty($userId) || $this->checkRememberMe()) {
            if (IS_AJAX) {
                returnJson(403, 202, 'error');
            } else {
                redirect('/Home/BookPage/index.html');
            }
        }
    }

    /**
     * 判断是否记住登录，即拥有登录cookie，调用前提是没有登录session
     * @modify AmosZhong 2015-01-28
     */
    private function checkRememberMe() {
        // 该项用于唯一限制用户登录，暂时没有用处
        // $guid = cookie(C('COOKIE_SERVER_REMEMBER_ME_UUID'));
        $userSSID = cookie(C('COOKIE_SERVER_REMEMBER_ME_USSID'));
        if (empty($userSSID)) {
            return false;
        }

        $RsaEncrypt = new \Org\Util\RSAEncrypt();
        $userId = $RsaEncrypt->meizhuDecrypt($userSSID);
        if (empty($userId)) {
            return false;
        }

        $userSSPS = cookie(C('COOKIE_SERVER_REMEMBER_ME_USSPS'));
        $passportTime = cookie(C('COOKIE_SERVER_REMEMBER_ME_PSTM'));
        $adminLoginLogic = A('Common/adminLogin', 'Logic');
        $adminLogin = $adminLoginLogic->getInfo($userId);
        if (empty($adminLogin)) {
            return false;
        }

        $expireTime = $passportTime + C('COOKIE_EXPIRE');
        if ($expireTime <= time()) {
            return false;
        }

        $compare = cookieUserSSPS($adminLogin['mobile'], $adminLogin['password'], $passportTime);
        if ($userSSPS !== $compare) {
            cookie(C('COOKIE_SERVER_REMEMBER_ME_UUID'), null);
            cookie(C('COOKIE_SERVER_REMEMBER_ME_USSID'), null);
            cookie(C('COOKIE_SERVER_REMEMBER_ME_USSPS'), null);
            cookie(C('COOKIE_SERVER_REMEMBER_ME_PSTM'), null);
            return false;
        }

        //清除原有session数据，登录
        session(null);
        // 存储基本信息到session
        session(C('USER_ID'), $adminLogin['id']);
        session(C('USER_NAME'), $adminLogin['name']);
        session(C('USER_MOBILE'), $adminLogin['mobile']);
        session(C('USER_HEAD'), $adminLogin['headpath']);
        return true;
    }

    /**
     * 赋值客栈列表到html页面
     * @modify AmosZhong 2016-01-06 创建
     */
    protected function assignHotel() {
        $userId = getUserId();
        $hotelLogic = A('Common/Hotel', 'Logic');
        $hotelList = $hotelLogic->getHotelByUser($userId);

        //查询当前用户信息
        $adminLoginLogic = A('Common/AdminLogin', 'Logic');
        $adminLogin = $adminLoginLogic->getInfo($userId);

        if (!IS_POST) {
            // 获取默认货币符号
            $currencyLogic = A('Common/Currency', 'Logic');
            $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($this->hotelId, true);
            $hotelDefaultSymbol = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['symbol'] : '¥';

            // 检查是否传入客栈ID
            // 若传入,校验是否是作为超级管理员是否,客栈是否禁用,若校验不通过,显示第一个启用的客栈
            $hotelList = getArrayValueAsIndex($hotelList, 'hotelentity_id');
            if ($this->hotelId > 0 && isset($hotelList[$this->hotelId]) && $hotelList[$this->hotelId]['status'] == 0) {
                $hotelName = $hotelList[$this->hotelId]['name'];
                $hotelRole = $hotelList[$this->hotelId]['role'];
                $hotelUsage = $hotelList[$this->hotelId]['usage'];
                $hotelEndDate = $hotelList[$this->hotelId]['enddate'];
                $universaltimeId = $hotelList[$this->hotelId]['universaltime_id'];
            } else {
                $enableDisableHotelList = getArrayValueAsIndex($hotelList, 'status', 'multi');
                $hotelName = null;
                $hotelRole = null;
                $this->hotelId = null;
                if (isset($enableDisableHotelList[0])) {
                    $hotelName = $enableDisableHotelList[0][0]['name'];
                    $hotelRole = $enableDisableHotelList[0][0]['role'];
                    $hotelUsage = $enableDisableHotelList[0][0]['usage'];
                    $hotelEndDate = $enableDisableHotelList[0][0]['enddate'];
                    $this->hotelId = $enableDisableHotelList[0][0]['hotelentity_id'];
                    $universaltimeId = $enableDisableHotelList[0][0]['universaltime_id'];
                }
            }

            //获取区号时区数据
            $universalTimeModel = D('UniversalTime');
            $universalTimeInfo = $universalTimeModel->field('areacode')->where(['id' => $universaltimeId])->find();
            $currentAreaCode = $universalTimeInfo ? $universalTimeInfo['areacode'] : '86';

            $this->assign('hotelDefaultSymbol', $hotelDefaultSymbol);
            $this->assign('adminLogin', $adminLogin);
            $this->assign('currentAreaCode', $currentAreaCode);
            $this->assign('currentHotel', $this->hotelId);
            $this->assign('hotelName', $hotelName);
            $this->assign("hotelRole", $hotelRole);
            $this->assign("hotelUsage", $hotelUsage);
            $this->assign("hotelEndDate", $hotelEndDate);
            $this->assign('navbarHotels', $hotelList);
            $this->assign('hasAdmin', in_array(1, array_unique(array_column($hotelList, 'role'))));
        }
    }

    /**
     * @description  获取用户登录状态
     * @modify songanwei 2016-01-09
     */
    protected function assignUser() {
        $this->assign('userName', session(C('USER_NAME')));
        $this->assign('userMobile', session(C('USER_MOBILE')));
        $this->assign('userHead', session(C('USER_HEAD')));
    }

    /**
     * @description 获取用户操作权限
     * @modify songanwei 2016-01-27
     */
    protected function assignAuthority() {
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        $userId = getUserId();
        $adminAuthority = $adminAuthorityLogic->show($this->hotelId, $userId);
        $this->assign('adminAuthority', $adminAuthority);

        return $adminAuthority;
    }

    /**
     * @description 是否是义卖客栈 
     * @modify wenhui 2017-09-12
     * @param int $hotelId 客栈id
     * @param int $maxRooms 最大房间数
     * @param int $count 房间数量
     */
    protected function checkUsageHotel($hotelId) {
        $hotelInfo = D('HotelEntity')->getInfo($hotelId);
        $roomInfo = D('RoomInfo')->getInfoByHotel($hotelId);
        $isMax = false;
        $isFreeHotel = false;
        if ($hotelInfo['usage'] == 4) {
            $isFreeHotel = true;
        }
        $existsRooms = isset($roomInfo) ? count($roomInfo) : 0;

        return array('isFreeHotel' => $isFreeHotel , 'existsRooms' => $existsRooms);
    }

    /**
     * @description 是否开启畅联代收 畅联代收是否过期
     * @modify wenhui 2017-09-12
     */
    protected function checkIsUclbrtPay($hotelId) {
        $hotelPayDetailInfo = D('HotelPayDetail')->getInfoByHotel($hotelId);
        $hotelPayUsableInfo = D('HotelPayUsable')->getInfo($hotelId);

        $isPayUclbrt = false;
        $currentDate = date('Y-m-d');
        if ($hotelPayUsableInfo['uclbrtalipayenable'] == 1 && $hotelPayUsableInfo['uclbrtalipayenddate'] > $currentDate) {
            // 代收 和 自收
            if ($hotelPayDetailInfo['type'] == '33') {
                if ($hotelPayUsableInfo['hotelwechatenable'] == 1 && $hotelPayUsableInfo['hotelwechatenddata'] > $currentDate) {
                    $isPayUclbrt = false;
                } else {
                    $isPayUclbrt = true;
                }
            } else if (in_array($hotelPayDetailInfo['type'], array('1','3'))) {
                $isPayUclbrt = true;
            }
        }
        if (!$isPayUclbrt) {
            if ($hotelPayUsableInfo['uclbrtwechatenable'] == 1 && $hotelPayUsableInfo['uclbrtwechatenddate'] > $currentDate) {
                // 代收 和 自收
                if ($hotelPayDetailInfo['type'] == '18') {
                    if ($hotelPayUsableInfo['hotelalipayenable'] == 1 && $hotelPayUsableInfo['hotelalipayenddate'] > $currentDate) {
                        $isPayUclbrt = false;
                    } else {
                        $isPayUclbrt = true;
                    }
                } else if (in_array($hotelPayDetailInfo['type'], array('2','3'))) {
                    $isPayUclbrt = true;
                }
            }
        }

        return $isPayUclbrt;
    }

     /**
     * @description 检查客栈是否有房间数量限制 
     * @modify wenhui 2017-12-18
     * @param int $hotelId 客栈id
     * @param int $roomCount 新增房间数
     * @return bool
     */
    protected function checkHotelRoomLimit($hotelId, $roomCount) {
        $hotelEntityModel = D('HotelEntity');
        $roomInfoModel = D('RoomInfo');

        $hotelData = $hotelEntityModel->getInfo($hotelId, false);
        if ($hotelData['roomlimit'] == 0) {
            return false; // 没限制
        }

        $roomInfo = $roomInfoModel->getInfoByHotel($hotelId);
        $existsRooms = isset($roomInfo) ? count($roomInfo) : 0;

        $totalRooms = $existsRooms + $roomCount;
        if ($totalRooms > $hotelData['roomlimit']) {
            return true; // 有限制
        } else {
            return false; // 没限制
        }
    }

    /**
     * 客栈默认货币
     * @modify wenhui 2018-02-05    创建
     */
    protected function getDefultCurrencyByHotel($hotel) {
        $currencyModel = D('Currency');
        $currencyHotelModel = D('CurrencyHotel');

        $bpCurrency = $currencyModel->getCurrencyInfo();
        $bpCurrency = getArrayValueAsIndex($bpCurrency, 'id');
        $defaultHotelCurrency = $currencyHotelModel->getDefaultCurrency($hotel);
        $defaultSymbol = isset($bpCurrency[$defaultHotelCurrency['currency_id']]['symbol']) ? $bpCurrency[$defaultHotelCurrency['currency_id']]['symbol'] : '¥';

        return $defaultSymbol;
    }
}
